/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.imenu.web.service;

import com.imenu.ejb.ImenuMenuFacade;
import com.imenu.ejb.ImenuTagFacade;
import com.imenu.entity.ImenuCourse;
import com.imenu.entity.ImenuMenu;
import com.imenu.entity.ImenuTag;
import com.sun.jersey.core.util.Base64;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 *
 * @author Yunzi
 */
@WebServlet(name = "XmlServlet", urlPatterns = {"/xmlServlet"})
public class XmlServlet extends HttpServlet {

    @EJB
    ImenuMenuFacade menuFacade;
    @EJB
    ImenuTagFacade tagFacade;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Enumeration<String> enu = request.getHeaderNames();
            while (enu.hasMoreElements()) {
                String name = enu.nextElement();
                System.out.println("Header name = " + name + " value = " + request.getHeader(name));
            }
            String command = request.getParameter("command");
            if ("adList".equals(command)) {
                out.write(this.adList(request, response));
            } else if ("menuInfo".equals(command)) {
                out.write(this.menuInfo(request, response));
            } else if ("cover".equals(command)) {
                out.write(this.cover(request, response));
            } else if ("course".equals(command)) {
                out.write(this.courseList(request, response));
            } else if ("checkUpdate".equals(command)) {
                out.write(this.checkUpdate(request, response));
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "不被支持的命令参数：[" + command + "]");
            }
        } finally {
            out.close();
        }
    }

    /**
     * 广告或推荐菜单列表
     * 返回XML，格式如下：
     * <?xml version="1.0" encoding="UTF-8"?>
     * <koubei_imenu_ad_list version="1.0">
     * <item id="1001" />
     * <item id="1002" />
     * <item id="1003" />
     * </koubei_imenu_ad_list>
     * 其中 item id是menuID
     */
    private String adList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.append("<koubei_imenu_ad_list version=\"1.0\">");
        List<ImenuMenu> list = this.menuFacade.findAll();
        System.out.println("XmlServlet.adList() this.menuFacade.findAll() = " + list);
        for (ImenuMenu menu : list) {
            sb.append("  <item id=\"").append(menu.getId()).append("\"/>");
        }
        sb.append("</koubei_imenu_ad_list>");
        return sb.toString();
    }
    /**
     * 检查菜单更新。客户端传过来菜单ID和updatetime列表，
     * 服务器端检查各个菜单是否需要更新，然后返回结果列表
     * <?xml version="1.0" encoding="UTF-8"?>
     * <koubei_imenu_list version="1.0">
     * <item id="1001" update="true"/>
     * <item id="1002" update="false"/>
     * <item id="1003" update="true"/>
     * </koubei_imenu_list>
     * 其中 item id是menuID
     */
    private String checkUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String param = request.getParameter("data");
        String[] ids = param.split(";");
        Map<Integer, Long> menusInfo = new HashMap<Integer, Long>();
        for(String one : ids){
            System.out.println("one = "+one);
            String[] pair = one.split(",");
            if(pair.length!=2) {
                System.out.println("one error : "+one);
                continue;
            }
            String id = pair[0];
            String time = pair[1];
            menusInfo.put(Integer.valueOf(id), Long.valueOf(time));
            System.out.println(new java.util.Date(Long.valueOf(time)*1000));
            System.out.println(new java.util.Date().getTime());
        }
        List<Integer> menuIds = new ArrayList<Integer>();
        for(Integer id : menusInfo.keySet()){
            menuIds.add(id);
        }
        List<ImenuMenu> menus = this.menuFacade.findByIds(menuIds);
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.append("<koubei_imenu_list version=\"1.0\">");
        for(ImenuMenu menu : menus){
            boolean update = menusInfo.get(menu.getId()) < menu.getUpdateTime().getTime();
            sb.append("  <item id=\"").append(menu.getId()).append("\" update=\"").append(update).append("\"/>");
        }
        sb.append("</koubei_imenu_list>");
        return sb.toString();
    }

    /**
     * 一个具体菜单的info信息，客户端传来唯一参数，menuid，
     * 返回menu信息，格式如下：
     * <?xml version="1.0" encoding="UTF-8"?>
     * <koubei_imenu_info version="1.0">
     * <store_id>AD1</store_id>
     * <city_id>310000</city_id>
     * <update_time>2011-05-24</update_time>
     * <lang>zh</lang>
     * <lang>en</lang>
     * <ad url="http://tuan.koubei.com/deal/10611200000000459"/>
     * </koubei_imenu_info>
     * 其中 store_id就是menuId，一个店只能有一份菜单。
     */
    private String menuInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer menuId = Integer.parseInt(request.getParameter("menuId"));
        ImenuMenu menu = this.menuFacade.find(menuId);
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.append("<koubei_imenu_info version=\"1.0\">");
        sb.append("<store_id>").append(menu.getStore().getId()).append("</store_id>");
        sb.append("<city_id>").append("").append("</city_id>");
        sb.append("<update_time>").append(menu.getUpdateTime().getTime()).append("</update_time>");
        sb.append("<lang>").append("zh").append("</lang>");
        sb.append("<ad url=\"http://tuan.koubei.com/deal/10611200000000459\"/>");
        sb.append("</koubei_imenu_info>");
        return sb.toString();
    }

    /**
     * 菜单封面信息，接受menuId，lang（语言）作为输入参数，输出XML描述菜单封面：
     * <?xml version="1.0" encoding="UTF-8"?>
     * <koubei_imenu_cover version="1.0">
     * <img>AD1.jpg</img> 
     * <title>6LGG5o2e6IKl576K54Gr6ZSF</title>
     * <name>6ICB5a2X5Y+35a2c54S26LGG5o2e6IKl576K54Gr6ZSF</name>
     * </koubei_imenu_cover>
     * 其中，img内容是一个文件名，但是这个文件名可以复原成为指向马良系统图片的地址：
     * http://img1.kbcdn.com/n01_a/cf09/f3/9f/c79294e4df59509bc6b18e2aec4a_300x400.jpg
     * 上面这个图片的地址，从n01_a开始，后面的部分，把斜线换成.来组成img元素的内容，即：
     * n01_a.cf09.f3.9f.c79294e4df59509bc6b18e2aec4a_300x400.jpg
     */
    private String cover(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer menuId = Integer.parseInt(request.getParameter("menuId"));
        String lang = request.getParameter("lang");
        ImenuMenu menu = this.menuFacade.find(menuId);
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.append("<koubei_imenu_cover version=\"1.0\">");
        sb.append("<img>").append(menu.getImagePortrait()).append("</img>");
        sb.append("<title>").append(menu.getTitle()).append("</title>");
        sb.append("<name>").append(menu.getName()).append("</name>");
        sb.append("</koubei_imenu_cover>");
        return sb.toString();
    }

    /**
     * 菜单的菜品信息，接受menuId，lang（语言）作为输入参数，输出XML描述菜单封面：
     *<?xml version="1.0" encoding="UTF-8"?>
     *<koubei_multimedia_terminal_screen version="1.0">
     *	<tag id="1" name="5Ya36I+c5Lqt" next="2">
     *		<section type="data">
     *			<item id="1">
     *				<img-big-v>MjAxMDA2MzAxNDUzMDYyNjYzMzMwLmpwZw==</img-big-v>
     *				<img-big-h>MjAxMDA2MzAxNDUzMDYyNjYzMzMwLmpwZw==</img-big-h>
     *				<img-middle>MjAxMDA2MzAxNDUzMDYyNjYzMzMwLmpwZw==</img-middle>
     *				<img-small>MjAxMDA2MzAxNDUzMDYyNjYzMzMwLmpwZw==</img-small>
     *				<title>6aG257qn5rW36JyH5aS0</title>
     *				<star>Mw==</star>
     *				<new>ZmFsc2U=</new>
     *				<hot>ZmFsc2U=</hot>
     *				<taste>5b6u5ZK444CB6YW4</taste>
     *				<recipe>5YeJ5ouM</recipe>
     *				<ingredients>5rW36JyH5aS0ODDlhYs=</ingredients>
     *				<price>MTU=</price>
     *				<description></description>
     *			</item>
     *			<item id="2">
     *				<img-big-v>MjAxMDA2MzAxNDUzMDYyNjYzMzMwLmpwZw==</img-big-v>
     *				<img-big-h>MjAxMDA2MzAxNDUzMDYyNjYzMzMwLmpwZw==</img-big-h>
     *				<img-middle>MjAxMDA2MzAxNDUzMDYyNjYzMzMwLmpwZw==</img-middle>
     *				<img-small>MjAxMDA2MzAxNDUzMDYyNjYzMzMwLmpwZw==</img-small>
     *				<title>5Y+k5Z+O6YWl6bG8</title>
     *				<star>Mw==</star>
     *				<new>dHJ1ZQ==</new>
     *				<hot>dHJ1ZQ==</hot>
     *				<taste>5ZK444CB6aaZ</taste>
     *				<recipe>5YeJ5ouM</recipe>
     *				<ingredients>5Li75paZODDlhYs=</ingredients>
     *				<price>MTI=</price>
     *				<description></description>
     *			</item>
     *		</section>
     *		<section type="layout">
     *			<page id="1">
     *				<frame id="1" left="0" top="0"
     *					   height="80" width="80" z-order="0">
     *					<textbox id="1" left="0" right="0"
     *							 height="30" width="80"
     *							 halign="center" valign="center"
     *							 wrap="true" z-order="0"
     *							 data_source="name" text="attribute_name">
     *						<border style="" width="1" />
     *						<font family="宋体"
     *							  size="12"
     *							  bold="false"
     *							  italic="false"
     *							  underline="false" />
     *						xOO6w6OsysC956Oh
     *						</textbox>
     *				</frame>
     *			</page>
     *		</section>
     *	</tag>
     *	<tag id="2" name="5rC05Lqn5bGL" next="3" prev="1">
     *		<section type="data">
     *		</section>
     *	</tag>
     *</koubei_multimedia_terminal_screen>
     * layout部分先不实现。
     * 其中 image-big-h是菜品大图横图，image-big-v菜品大图竖图，image-middle菜品详情图，image-small菜品列表图
     */
    private String courseList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer menuId = Integer.parseInt(request.getParameter("menuId"));
        String lang = request.getParameter("lang");
        ImenuMenu menu = this.menuFacade.find(menuId);
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.append("<koubei_multimedia_terminal_screen version=\"1.0\">");
        //根据menuId查找ImenuMenu
        Collection<ImenuCourse> courses = menu.getImenuCourseCollection();
        //Map<tagId, List<ImenuCourse>>
        Map<ImenuTag, List<ImenuCourse>> courseByTag = new HashMap<ImenuTag, List<ImenuCourse>>();
        for (ImenuCourse course : courses) {
            if (courseByTag.get(course.getTag()) == null) {
                courseByTag.put(course.getTag(), new ArrayList<ImenuCourse>());
            }
            courseByTag.get(course.getTag()).add(course);
        }
        for (ImenuTag tag : courseByTag.keySet()) {
            sb.append("<tag id=\"").append(tag.getId()).append("\" name=\"").append(tag.getName()).append("\">");
            sb.append("  <section type=\"data\">");
            List<ImenuCourse> list = courseByTag.get(tag);
            if (list != null) {
                for (ImenuCourse course : list) {
                    sb.append("    <item id=\"").append(course.getId()).append("\">");
                    String fileTypeP = course.getPortraitImage().substring(course.getPortraitImage().lastIndexOf("."));
                    String fileTypeL = course.getLandscapeImage().substring(course.getLandscapeImage().lastIndexOf("."));
                    String fileNameP = course.getPortraitImage().substring(0, course.getPortraitImage().lastIndexOf("."));
                    String fileNameL = course.getLandscapeImage().substring(0, course.getLandscapeImage().lastIndexOf("."));
                    sb.append("      <img-big-v>").append(Base64.encode(course.getPortraitImage())).append("</img-big-v>");
                    sb.append("      <img-big-h>").append(Base64.encode(course.getLandscapeImage())).append("</img-big-h>");
                    sb.append("      <img-middle>").append(Base64.encode(fileNameL + "_440x330" + fileTypeL)).append("</img-middle>");
                    sb.append("      <img-small>").append(Base64.encode(fileNameL + "_300x225" + fileTypeL)).append("</img-small>");

                    sb.append("      <title>").append(Base64.encode(course.getName())).append("</title>");
                    sb.append("      <star>").append(Base64.encode(course.getStar() + "")).append("</star>");
                    sb.append("      <create-time>").append(Base64.encode(new SimpleDateFormat("yyyy-MM-dd").format(course.getCreateTime()))).append("</create-time>");//
                    sb.append("      <hot>").append(Base64.encode(course.getName())).append("</hot>");
                    sb.append("      <taste>").append(Base64.encode("taste")).append("</taste>");
                    sb.append("      <recipe>").append(Base64.encode(course.getRecipe())).append("</recipe>");
                    sb.append("      <ingredients>").append(Base64.encode("ingredients")).append("</ingredients>");
                    sb.append("      <price>").append(Base64.encode(course.getPrice() + "")).append("</price>");
                    sb.append("      <description>").append(Base64.encode("description")).append("</description>");
                    sb.append("    </item>");
                }
            }
            sb.append("  </section>");
            sb.append("</tag>");
        }
        sb.append("</koubei_multimedia_terminal_screen>");
        return sb.toString();
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
